package org.commonmark.internal.util;

import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class Html5EntitiesUtil {
    private static final String TAG = "luzhen";
    private static HiLogLabel sLogLabel;
    private static final int DOMAIN = 0x001;

    private static HiLogLabel createLogLabel() {
        if (sLogLabel == null) {
            sLogLabel = new HiLogLabel(HiLog.LOG_APP, DOMAIN, TAG);
        }
        return sLogLabel;
    }

    public static void info(String format, Object... objects) {
        HiLog.info(createLogLabel(), format, objects);
    }

    public static void initEntities() {
        Map<String, String> entities = new HashMap<>();
        InputStream stream = Html5EntitiesUtil.class.getClassLoader().getResourceAsStream(Html5Entities.ENTITY_PATH);
        Charset charset = StandardCharsets.UTF_8;
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream, charset))) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                if (line.length() == 0) {
                    continue;
                }
                int equal = line.indexOf('=');
                String key = line.substring(0, equal);
                String value = line.substring(equal + 1);
                entities.put(key, value);
            }
        } catch (IOException e) {
            throw new IllegalStateException("Failed reading data for HTML named character references", e);
        }
        entities.put("NewLine", "\n");
        Html5Entities.NAMED_CHARACTER_REFERENCES = entities;
    }
}
